package fr.nekloth.android.hinode;

import java.util.Date;

import uk.me.jstott.sun.Time;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import android.os.CountDownTimer;


/**
 * @author  NEKLOTH
 * @email   nekloth@gmail.com
 * 
 */

public class alarmReceiverDisplay extends Activity {
	
	//CONSTANTS
	public int MUSIC_LOOP_COUNTER = 3;
	public String MYPREFS = "hinode_application_settings";

	static final int MENU_VOLUME_SILENCE = 4;
	static final int MENU_VOLUME_LOW = 5;
	static final int MENU_VOLUME_MEDIUM = 6 ;
	static final int MENU_VOLUME_HIGH = 7;
	
	final static float MUSIC_VOLUME_SILENCE_LEVEL = 0.0f;
	final static float MUSIC_VOLUME_LOW_LEVEL = 0.05f;
	final static float MUSIC_VOLUME_MEDIUM_LEVEL = 0.15f;
	final static float MUSIC_VOLUME_HIGH_LEVEL = 0.40f;
		
	final static int STREAM_TO_USE = AudioManager.STREAM_MUSIC;
	
	//Obsolete
	public static int selectedVolumeLevel = MENU_VOLUME_MEDIUM;
	
	public static int selectedTone = applicationStartup.MENU_TONE_POP;
	String MP3File_Selected;
	
	
	
	//For the MUSIC
	MediaPlayer mp;
	AudioManager am;
	int inTheLoop = 0 ;
	int originalVolume;
	int readMusicIndex = 0;
	
	int initialStreamVolume = -1;
	int initialSystemStreamVolume = -1;
	
	
	//For Vibration
    Vibrator vibratorInstrument;
	long[] vibrateTone = {400,200,400,200,400,200,200,400,100,200,100,600,200,400,100,200,100,600};
	
	//For the ANIMATION
	 ImageView rocketImage;
	 AnimationDrawable rocketAnimation;
	
	//GUI
	Button okButton;
	Context theContext;
	
	//Alarms
	Time time1, time2;
	Date refDate ;
	int referenceTime;
	String[] alarmTime = {"",""};

	int mode ;
	SharedPreferences mySharedPreferences ;

    private NotificationManager mNotificationManager;
    
    public int MY_APP_NOTIFICATION_ID = 24072706;
    public int MY_APP_NOTIFICATION_ID_TRIGGER = 240727062;
	
	//-------------------------------------------------------------------------------------------------
	// FOR DEVELOPMENT ENVIRONMENT ONLY : DO NOT FORGET TO FALSE FOR PRODUCTION
	//-------------------------------------------------------------------------------------------------
	boolean debugMode = false;
	
	boolean alarm1ToDesactivate = false, alarm2ToDesactivate = false;
	
	boolean alarm1IsActive = false, alarm2IsActive = false;
	
	
	// For WAKE LOCK
	   public static final String MY_APPLICATION_NAMING_CONSTANT = "fr.nekloth.android.hinode";
	   private PowerManager.WakeLock wakeLock = null;
	   private KeyguardManager.KeyguardLock keyLock = null;
	   private static long WakeUpDurationInMilliseconds = 20000;
	
	public void findMusicTune() {
		//LOAD DATA
		try {
        	int mode = Activity.MODE_PRIVATE;  
        	SharedPreferences mySharedPreferences = theContext.getSharedPreferences(applicationStartup.MYPREFS,mode);
        	selectedTone = mySharedPreferences.getInt("general_tone", applicationStartup.MENU_TONE_POP);
        	MP3File_Selected = mySharedPreferences.getString(SelectToneActivity.KEY_MP3FILE_PREFERENCE, "none");
		} catch (Exception e) {
			toastShortInfo("Error in loading data (" + e.getMessage() + ")");
		}
	}
	   
	   
    public void loadVolumeOnly() {
    	try {
        	int mode = Activity.MODE_PRIVATE;  
        	SharedPreferences mySharedPreferences = theContext.getSharedPreferences(applicationStartup.MYPREFS,mode);
        	selectedVolumeLevel = mySharedPreferences.getInt("general_volume_level", MENU_VOLUME_MEDIUM);
        	selectedVolumeLevel = mySharedPreferences.getInt(SelectToneActivity.KEY_VOLUME_PREFERENCE, MENU_VOLUME_MEDIUM);
    	} catch (Exception e) {
    		applicationStartup.toastInfo(theContext,"Error loading volume level (" + e.getMessage() + ")");
    	}
    }
	    
	public void playVibrateSong(Context theContext) {
		try {
	        vibratorInstrument.vibrate(vibrateTone, -1);
		} catch (Exception e) {
			Toast.makeText(this, "Vibration exception: " + e.getMessage() ,Toast.LENGTH_LONG).show();
		}
	}
	
	public void playMusic(Context theContext) {
		
		backupVolumeSettings();

		//- PLAY SOUND --------------------------------------------------------------------------------
		try {
			mp = new MediaPlayer(); 
			findMusicTune();
			
			//mp = MediaPlayer.create(theContext, selectedTone);
			try {
			    mp.reset();
			    mp.setDataSource(MP3File_Selected);
			    Log.d("Nekloth","MediaPlayer : DataSource Set to " + MP3File_Selected);
			    mp.prepare();
			    MUSIC_LOOP_COUNTER = 1;
		    } catch (Exception e) {
		    	mp = MediaPlayer.create(this, R.raw.pop);
		    	MUSIC_LOOP_COUNTER = 3;
		    }

			
			mp.setScreenOnWhilePlaying(true);
	        mp.setAudioStreamType(STREAM_TO_USE);

	        am = (AudioManager) theContext.getSystemService(Context.AUDIO_SERVICE);	
	        am.setStreamVolume(STREAM_TO_USE, am.getStreamMaxVolume(STREAM_TO_USE), 0);
	        
	        mp.setVolume(MUSIC_VOLUME_MEDIUM_LEVEL, MUSIC_VOLUME_MEDIUM_LEVEL);
	    	switch (selectedVolumeLevel) {
	    	  case MENU_VOLUME_SILENCE: mp.setVolume(MUSIC_VOLUME_SILENCE_LEVEL, MUSIC_VOLUME_SILENCE_LEVEL);break;
	    	  case MENU_VOLUME_LOW: mp.setVolume(MUSIC_VOLUME_LOW_LEVEL, MUSIC_VOLUME_LOW_LEVEL);break;
	    	  case MENU_VOLUME_MEDIUM: mp.setVolume(MUSIC_VOLUME_MEDIUM_LEVEL, MUSIC_VOLUME_MEDIUM_LEVEL);break;
	    	  case MENU_VOLUME_HIGH: mp.setVolume(MUSIC_VOLUME_HIGH_LEVEL, MUSIC_VOLUME_HIGH_LEVEL);break;
	      	}
	        mp.start();
	        Log.d("Nekloth","Playing music");
	        mp.setOnCompletionListener(new OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					if (++inTheLoop < MUSIC_LOOP_COUNTER) { 
						mp.start(); 
					} else {
						restoreVolumeSettings();
					}
				}
			});
		} catch (Exception e) {
			Toast.makeText(this, "Music exception: " + e.getMessage(),Toast.LENGTH_SHORT).show();
		}
	}

	public void onWindowFocusChanged (boolean hasFocus) {
    	rocketAnimation.start();
	}
	
    protected void toastShortInfo(String theMessage) {
    	Toast.makeText(this, theMessage,Toast.LENGTH_SHORT).show();
    }
	
    public void refreshNotifications() {
    	    	
    	mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	mNotificationManager.cancel(MY_APP_NOTIFICATION_ID);

    	loadAlarmStatus();
		if (alarm1IsActive|| alarm2IsActive) {
			CharSequence from = getText(R.string.app_name) + "";	
			String message = "";
			if (alarm1IsActive) { //ALARM1
				message += getText(R.string.t_alarm) + " " + getText(R.string.activated);
				message +=  " - "+ alarmTime[0];
				
			} else { //ALARM2
				message += getText(R.string.t_alarm) + " " + getText(R.string.activated);
				message +=  " - " + alarmTime[1];
				
			}
			
	        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, applicationStartup.class), 0);
	        String tickerText = (String) message;
	        Notification notif_activated = new Notification(R.drawable.icon_sun, tickerText, System.currentTimeMillis());
	        notif_activated.setLatestEventInfo(this, from, message, contentIntent);
	        notif_activated.flags |= Notification.FLAG_NO_CLEAR;
	        mNotificationManager.notify(MY_APP_NOTIFICATION_ID, notif_activated);
		}
		
    	
    	//Prepare "Alarm Triggered" notification
    	CharSequence from = getText(R.string.app_name) + "";
    	String message = (String) getText(R.string.SCHED_alarm_triggered);    		
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, alarmReceiverDisplay.class), 0);
    	String tickerText = (String) message;
    	Notification notif = new Notification(R.drawable.icon_trig, tickerText, System.currentTimeMillis());
    	notif.setLatestEventInfo(this, from, message, contentIntent);
    	notif.ledARGB = Color.BLUE;
    	notif.ledOnMS = 500;
    	notif.ledOffMS = 100;
    	notif.flags = Notification.FLAG_SHOW_LIGHTS;
    	mNotificationManager.notify(MY_APP_NOTIFICATION_ID_TRIGGER, notif);
    }
    
    public void loadAlarmStatus() {
    	mode = Activity.MODE_PRIVATE;
    	SharedPreferences mySharedPreferences = theContext.getSharedPreferences(MYPREFS,mode);    	
    	
    	try{
	    	alarm1IsActive = mySharedPreferences.getBoolean("alarm1_activeStatus", false);
	    	alarm2IsActive = mySharedPreferences.getBoolean("alarm2_activeStatus", false);
	    	alarmTime[0] = mySharedPreferences.getString("alarm1_NOTIFY", "null");
	    	alarmTime[1] = mySharedPreferences.getString("alarm2_NOTIFY", "null");
    	} catch (Exception e) {
    		toastShortInfo("Error during load alarm activation info (" + e.getMessage() +")");
    	}
    }
    
    
    public void desactivateNeededAlarm() {

    	mode = Activity.MODE_PRIVATE;
    	SharedPreferences mySharedPreferences = theContext.getSharedPreferences(MYPREFS,mode);

    	String readTime ="";
    	int readHour = 0, readMinuts = 0;
    	
    	try{
	    	readTime = mySharedPreferences.getString("alarm1_AlarmTime","11:50");
	    	readHour = Integer.parseInt(readTime.substring(0,2));
	    	readMinuts = Integer.parseInt(readTime.substring(3, 5));
	    	time1 = new Time(readHour, readMinuts, 0.0d);
	    	referenceTime = mySharedPreferences.getInt("triggerTime", 0000);
	    	if (referenceTime == time1.getCondensedVersion()) {
		    	if (debugMode) toastShortInfo("Alarm 1 desactivate");
		    	alarm1ToDesactivate = true;
	    	}
    	} catch (Exception e) {
    		toastShortInfo("Error during load alarm 1 info (" + e.getMessage() +")");
    	}
    	
    	try  {
	    	readTime = mySharedPreferences.getString("alarm2_AlarmTime","11:50");
	    	readHour = Integer.parseInt(readTime.substring(0,2));
	    	readMinuts = Integer.parseInt(readTime.substring(3, 5));
	    	time2 = new Time(readHour, readMinuts, 0.0d);
	    	referenceTime = mySharedPreferences.getInt("triggerTime", 0000);
	    	if (referenceTime == time2.getCondensedVersion()) {
		    	if (debugMode) toastShortInfo("Alarm 2 to desactivate");
		    	alarm2ToDesactivate = true;
	    	}
    	} catch (Exception e) {
    		toastShortInfo("Error during load alarm 2 info (" + e.getMessage() +")");
    	}
    	
    	saveDesactivation();
    	
    }

    public void saveDesactivation() {

    	mode = Activity.MODE_PRIVATE;
    	SharedPreferences mySharedPreferences = theContext.getSharedPreferences(MYPREFS,mode);

    	try {
	    	SharedPreferences.Editor editor = mySharedPreferences.edit();
	    	if (alarm1ToDesactivate) editor.putBoolean("alarm1_activeStatus", false);
	    	if (alarm2ToDesactivate) editor.putBoolean("alarm2_activeStatus", false);
	    	editor.commit();
	    	if (debugMode) toastShortInfo("Alarm desactivated");
   	    	} catch (Exception e) {
   	    		toastShortInfo("Error during SAVING");
   	    	}
    }
    
    public void launchApplicationStartupActivity(){
	    Intent intentToLaunch = new Intent();		    
		intentToLaunch.setClass(this, applicationStartup.class);
		intentToLaunch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		this.startActivity(intentToLaunch);
    }
    
	private boolean backupVolumeSettings() {
		boolean done = false;
		AudioManager am;
		try {
			am = (AudioManager) theContext.getSystemService(Context.AUDIO_SERVICE);
			initialStreamVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
			initialSystemStreamVolume = am.getStreamVolume(AudioManager.STREAM_SYSTEM);
			Log.d("Nekloth","Saved volume (music,system) = (" + initialStreamVolume + "," + initialSystemStreamVolume + ")");
			done = true;
		} catch (Exception e) {
			Log.d("Nekloth","Initialisation error (" + e.getMessage() + ")");
		}
		return done;
	}
	
	private boolean restoreVolumeSettings() {
		boolean done = false;
		AudioManager am;
		try {
			am = (AudioManager) theContext.getSystemService(Context.AUDIO_SERVICE);
			am.setStreamVolume(AudioManager.STREAM_MUSIC, initialStreamVolume, 0);
			am.setStreamVolume(AudioManager.STREAM_SYSTEM, initialSystemStreamVolume, 0);
			Log.d("Nekloth","Restored volume (music,system) = (" + initialStreamVolume + "," + initialSystemStreamVolume + ")");
			done = true;
		} catch (Exception e) {
			Log.d("Nekloth","Restore error (" + e.getMessage() + ")");
		}
		return done;
	}

    
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

    	theContext = this;
    	super.onCreate(savedInstanceState);
    	
    	//GET LOCK TO TURN SCREEN ON
    	final PowerManager pm =    (PowerManager)this.getSystemService(Context.POWER_SERVICE);
    	wakeLock = pm.newWakeLock((PowerManager.FULL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP), MY_APPLICATION_NAMING_CONSTANT);
    	KeyguardManager km = (KeyguardManager)this.getSystemService(Context.KEYGUARD_SERVICE);
    	keyLock = km.newKeyguardLock(MY_APPLICATION_NAMING_CONSTANT);
    	wakeLock.acquire();
     	keyLock.disableKeyguard();

     	loadAlarmStatus();
     	loadVolumeOnly();
     	
        setContentView(R.layout.alarm_receiver_activity);
        
        inTheLoop = 0;

        //Needed services
		am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        vibratorInstrument = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        
        //Defining the FONT to the title TextView
        Typeface face=Typeface.createFromAsset(getAssets(), applicationStartup.GLOBAL_FONT_TO_USE);
        TextView tv=(TextView)findViewById(R.id.alarm_receiver_title);
        tv.setTypeface(face);
        
        tv=(TextView)findViewById(R.id.strwakeup);
        
        Date theDate = new Date();
        tv.setText(tv.getText() + " "+ theDate.getHours() + ":" + theDate.getMinutes());
        tv.setGravity(Gravity.CENTER);
        
        //Prepare the animation
        ImageView rocketImage = (ImageView) findViewById(R.id.imgalarmlogo);
        rocketImage.setBackgroundResource(R.drawable.alarm_animation);
        rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
        
//		if (am.getRingerMode()>1) { //Not silent nor vibrate mode !
			playVibrateSong(getBaseContext());
			playMusic(getBaseContext());
//		} else {
//			playVibrateSong(getBaseContext());
//		}
        
        okButton = (Button) findViewById(R.id.btnAcknowledgement);
        okButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				try {
					inTheLoop = 99;
					if (mp!=null) {if (mp.isPlaying()) mp.stop();}
			    	mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
			    	mNotificationManager.cancel(MY_APP_NOTIFICATION_ID_TRIGGER);
					finish();
				} catch (Exception e) {
					toastShortInfo("Non managed error (" + e.getMessage()+")");
				}
				
			}
        });
        
    	refDate = new Date();
    	referenceTime = (refDate.getHours() * 100) + refDate.getMinutes();

    	desactivateNeededAlarm();
    	
    	refreshNotifications();
    	
    	CountDownTimer cdTimer =  new CountDownTimer(WakeUpDurationInMilliseconds, 1000) {
    	     public void onTick(long millisUntilFinished) {
    	    	 //Do nothing onTick... Sorry
    	     }

    	     public void onFinish() {
    	    	 //Free the LOCKS
    	         if(null != wakeLock) {
    	        	 wakeLock.release();
    	        	 wakeLock = null;
    	         }
    	         if(null != keyLock) {
    	        	 keyLock.reenableKeyguard();
    	        	 keyLock = null;
    	         }
    	     }
    	  };
    	
    	cdTimer.start();
    	
    } // End of OnCreate

    
    @Override
    protected void onDestroy()
    {
    	// FREE THE LOCK !
        if(null != wakeLock) {
       	 wakeLock.release();
       	 wakeLock = null;
        }
        if(null != keyLock) {
       	 keyLock.reenableKeyguard();
       	 keyLock = null;
        }
        super.onDestroy();
    }   
}
